using Newtonsoft.Json;
using System;
using BanZuiCloudControlAgent.Utils.Common;

namespace BanZuiCloudControlAgent.Core.Mqtt.Models
{
    /// <summary>
    /// 更新任务负载模型
    /// </summary>
    public class UpdateTaskPayloadModel
    {
        /// <summary>
        /// 下载链接
        /// </summary>
        [JsonProperty("downloadUrl")]
        public string DownloadUrl { get; set; }

        /// <summary>
        /// 版本号
        /// </summary>
        [JsonProperty("version")]
        public string Version { get; set; }

        /// <summary>
        /// 是否强制更新
        /// </summary>
        [JsonProperty("forceUpdate")]
        public bool ForceUpdate { get; set; }

        /// <summary>
        /// 更新说明
        /// </summary>
        [JsonProperty("description")]
        public string Description { get; set; }

        /// <summary>
        /// 更新发布时间
        /// </summary>
        [JsonProperty("releaseTime")]
        public DateTime ReleaseTime { get; set; }
    }

    /// <summary>
    /// 更新任务模型，用于接收服务器推送的更新任务
    /// </summary>
    public class UpdateTaskModel : BaseMessageModel
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public UpdateTaskModel() : base()
        {
            MessageType = MessageTypeConstants.UPDATE_TASK;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="deviceCode">设备码</param>
        /// <param name="payload">更新任务负载</param>
        public UpdateTaskModel(string deviceCode, UpdateTaskPayloadModel payload)
            : base(MessageTypeConstants.UPDATE_TASK, deviceCode, payload)
        {
        }

        /// <summary>
        /// 获取更新任务负载
        /// </summary>
        /// <returns>更新任务负载</returns>
        public UpdateTaskPayloadModel GetPayload()
        {
            if (Payload == null)
                return null;
                
            if (Payload is UpdateTaskPayloadModel payloadModel)
                return payloadModel;
                
            // 尝试将Payload转换为UpdateTaskPayloadModel
            try
            {
                // 如果Payload是JObject或其他JSON对象，尝试转换
                return JsonHelper.Convert<object, UpdateTaskPayloadModel>(Payload);
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 下载链接
        /// </summary>
        public string DownloadUrl => (GetPayload()?.DownloadUrl);

        /// <summary>
        /// 版本号
        /// </summary>
        public string Version => (GetPayload()?.Version);

        /// <summary>
        /// 是否强制更新
        /// </summary>
        public bool ForceUpdate => (GetPayload()?.ForceUpdate ?? false);

        /// <summary>
        /// 更新说明
        /// </summary>
        public string Description => (GetPayload()?.Description);

        /// <summary>
        /// 更新发布时间
        /// </summary>
        public DateTime? ReleaseTime => (GetPayload()?.ReleaseTime);
    }
} 